import java.util.SortedMap;

/**
 * @author zhangdi
 * @version 1.0
 * @date 2022.6.29 15:49
 */
public class ConsistencyHashWithVirtual {
    public static void main(String[] args) {
        HashInfo hashInfo = new HashInfo();
        for (String server : hashInfo.servers) {
            long ha = Math.abs(server.hashCode()>>>16);
            hashInfo.serverMap.put(ha, server);
            for (int i = 0; i < hashInfo.virtualCount; i++) {//每个服务器生成virtualCount个虚拟节点
                long virHash = Math.abs((server + "#" + i).hashCode());
                hashInfo.serverMap.put(virHash, server);
                System.out.println("服务器" + server + "的虚拟节点#" + i + "映射到Hash值为" + virHash);
            }
        }
        int c = 1000;
        hashInfo.ids = new String[c];
        do {
            hashInfo.ids[c -= 1] = c + "";
        } while (c > 0);

        for (String id : hashInfo.ids) {
            long idHash = id.hashCode();
            SortedMap<Long, String> hitServerMap = hashInfo.serverMap.tailMap(idHash);
            if (hitServerMap.isEmpty()) {
                System.out.println("id " + id + "被路由到" + hashInfo.serverMap.firstKey() + "(" + hashInfo.serverMap.get(hashInfo.serverMap.firstKey()) + ")服务器");
            } else {
                System.out.println("id " + id + "被路由到" + hitServerMap.firstKey() + "(" + hashInfo.serverMap.get(hitServerMap.firstKey()) + ")服务器");
            }
        }
    }
}
